<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
	/**
	 * Авторизация контактика удалась..
	 * но не найдено соответствия с юзером имхонета
	 * не стоит этого стыдиться..
	 */
	const NEW_USER = 101;
	
	private $_id;

	public $vkSession = array();
	
	public function __construct()
	{
		$session=new CHttpSession;
  		$session->open();
  		
		$this->vkSession = $session['vk_params'];
	}
	
	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$session=new CHttpSession;
  		$session->open();

		if ( is_array($this->vkSession) )
		{
			$viewer_id = $this->vkSession['viewer_id'];
			
			Yii::app()->Imhonet->setAuthParams($this->vkSession);
			$data = Yii::app()->Imhonet->run('login');

			if ($data->auth_user) 
			{
				$this->_id = $viewer_id;
				$this->setState('vkSession', $this->vkSession);
				unset($session['vk_params']);

				$this->errorCode = self::ERROR_NONE;
			}
			elseif ($data->new_user)
				$this->errorCode = self::NEW_USER;
			else
				$this->errorCode = self::ERROR_UNKNOWN_IDENTITY;
		}

		return !$this->errorCode;
	}
	
 	public function getId()
    {
        return $this->_id;
    }
    
}
